package com.wish.finance.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.wish.common.core.usconfig.common.MsgResult;
import com.wish.finance.entity.vo.FactoringVo;
import com.wish.finance.service.ITJrFactoringDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author benjamin
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/factoring-detail")
public class TJrFactoringDetailController {

    @Autowired
    ITJrFactoringDetailService itJrFactoringDetailService;

    @GetMapping("/detailList")
    public MsgResult detailList(FactoringVo vo) {
        PageInfo<FactoringVo> pg = itJrFactoringDetailService.detailList(vo);
        return MsgResult.succeed(pg);
    }

    @GetMapping("/exportExcel")
    public void exportExcel(FactoringVo vo, HttpServletResponse response) throws IOException {
        // 获取要导出的数据集合
        List<FactoringVo> list = itJrFactoringDetailService.exportExcel(vo);
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 这一步没有必要
        ArrayList<FactoringVo> rows = CollUtil.newArrayList(list);
        writer.addHeaderAlias("contractNo", "申请合同号");
        writer.addHeaderAlias("businessName", "公寓名称");
        writer.addHeaderAlias("roomName", "承租房间");
        writer.addHeaderAlias("tenantName", "租客姓名");
        writer.addHeaderAlias("shouldMonthRent", "应还保理租金");
        writer.addHeaderAlias("borrowedStart", "借款账期开始日");
        writer.addHeaderAlias("borrowedEnd", "借款账期截止日");
        writer.addHeaderAlias("realCollection", "交租日期");
        writer.addHeaderAlias("capName", "资金方");
        // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);

        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

}
